package com.imooc.security.user;

import com.lambdaworks.crypto.SCryptUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.Valid;
import java.util.List;

/**
 * @ClassName UserServiceImpl
 * @Description TODO
 * @Author wushaopei
 * @Date 2020/10/17 13:31
 * @Version 1.0
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public UserInfo create( @Valid UserInfo userInfo) {
        /**
         *  将密码加密成明文
         */
        User user = new User();
        BeanUtils.copyProperties(userInfo,user);
        // 加密
        user.setPassword(SCryptUtil.scrypt(user.getPassword(),32768,8,1));
        userRepository.save(user);
        userInfo.setId(user.getId());
        return userInfo;
    }

    @Override
    public UserInfo update(UserInfo user) {
        return user;
    }

    @Override
    public void delete(Long id) {

    }

    @Override
    public UserInfo get(Long id) {
//        return userRepository.findById(id).get().buildInfo();
        User user = userRepository.findById(id).get();
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(user,userInfo);
        return userInfo;
    }

    @Override
    public List<UserInfo> query(String name) {
        return null;
    }

    @Override
    public UserInfo login(UserInfo userInfo) {

        User user = userRepository.findByUsername(userInfo.getUsername());
        if(user == null && SCryptUtil.check(userInfo.getPassword(),user.getPassword())) {
            throw new RuntimeException("身份认证信息异常，获取用户信息失败");
        }
        UserInfo info = new UserInfo();
        info.setPermissions(user.getPermissions());
        user.setPassword("");
        BeanUtils.copyProperties(user,info);
        return info;
    }
}
